unit FtpUnit;

interface

uses
  Windows, Classes,Wininet;

type
  TFtpThread = class(TThread)
  private
    TheisGetPut:Boolean;
    TheIpaddStr:String;
    ThePort:integer;
    TheUser:String;
    ThePass:String;
    TheFFile:String;
    TheLFile:String;
  protected
    procedure Execute; override;
  Public
    constructor Create(isGetorPut:Boolean;IpaddStr:String;Port:integer;User:String;Pass:String;FFile:String;LFile:String);
    destructor Destroy; override;
    function DownloadFtp:Boolean;
    function UpFtp:Boolean;
  end;

implementation 
uses MainServer;

constructor TFtpThread.Create(isGetorPut:Boolean;IpaddStr:String;Port:integer;User:String;Pass:String;FFile:String;LFile:String);
begin
   inherited Create(True);
   try   
     TheisGetPut:=isGetorPut;
     TheIpaddStr:=IpaddStr;
     ThePort:=Port;
     TheUser:=User;
     ThePass:=Pass;
     TheFFile:=FFile;
     TheLFile:=LFile;
   except
   end;
   FreeOnTerminate:=True;
   Suspended := False;
end;

function TFtpThread.DownloadFtp:Boolean;
var
FINet: HINTERNET;
FContext: Integer;
FFtpHandle: HInternet;
begin
Result:=False;
FINet:= InternetOpen('WinINet', 0, nil, nil, 0);
if FINet=nil then
begin
InternetCloseHandle(FINet);
Exit;
end;
FContext := 255;
FftpHandle := InternetConnect(FINet, PChar(TheIpaddStr), ThePort,
  PChar(TheUser), PChar(ThePass),
  Internet_Service_Ftp, 0, FContext);
 if FFtpHandle = nil then
 begin
 InternetCloseHandle(FINet);
 InternetCloseHandle(FFtpHandle);
 Exit;
 end;
Result := FtpGetFile(FFTPHandle, PChar(TheFFile), PChar(TheLFile),False, File_Attribute_Normal,Ftp_Transfer_Type_Binary, 0);
if FINet <> nil then InternetCloseHandle(FINet);
if FFtpHandle <> nil then InternetCloseHandle(FFtpHandle);
end;

function TFtpThread.UpFtp:Boolean;
var
FINet: HINTERNET;
FContext: Integer;
FFtpHandle: HInternet;
begin
Result:=False;
FINet:= InternetOpen('WinINet', 0, nil, nil, 0);
if FINet=nil then
begin
InternetCloseHandle(FINet);
Exit;
end;
FContext := 255;
FftpHandle := InternetConnect(FINet, PChar(TheIpaddStr), ThePort,
  PChar(TheUser), PChar(ThePass),
  Internet_Service_Ftp, 0, FContext);
 if FFtpHandle = nil then
 begin
 InternetCloseHandle(FINet);
 InternetCloseHandle(FFtpHandle);
 Exit;
 end;
Result:=FtpPutFile(FFTPHandle, PChar(TheLFile), PChar(TheFFile), FTP_TRANSFER_TYPE_BINARY, 1);
if FINet <> nil then InternetCloseHandle(FINet);
if FFtpHandle <> nil then InternetCloseHandle(FFtpHandle);
end;

procedure TFtpThread.Execute;
begin
try
  if TheisGetPut then 
    begin
      while not UpFtp do
        begin
          Sleep(30000);
        end;
    end else begin
      while not DownloadFtp do
        begin
          Sleep(30000);
        end;    
    end;          
except
end;
Self.Terminate;
end;

destructor TFtpThread.Destroy;
begin
  inherited destroy;
end;
end.
